"""
数据库连接管理
提供同步和异步的数据库会话
"""
from contextlib import contextmanager
from typing import Generator
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session, declarative_base
from sqlalchemy.pool import QueuePool
from config.settings import settings
from utils.logger import app_logger

# 创建数据库引擎
engine = create_engine(
    settings.database_url,
    poolclass=QueuePool,
    pool_size=settings.db_pool_size,
    max_overflow=settings.db_max_overflow,
    pool_pre_ping=True,  # 连接前检查连接是否有效
    pool_recycle=3600,   # 1小时回收连接
    echo=False,  # 禁用SQL日志输出（避免过多日志）
)

# 创建Session工厂
SessionLocal = sessionmaker(
    bind=engine,
    autocommit=False,
    autoflush=False,
    expire_on_commit=False,
)

# ORM基类
Base = declarative_base()


@contextmanager
def get_sync_session() -> Generator[Session, None, None]:
    """
    获取同步数据库会话（上下文管理器）

    使用示例:
        with get_sync_session() as session:
            result = session.query(User).all()
    """
    session = SessionLocal()
    try:
        yield session
        session.commit()
    except Exception as e:
        session.rollback()
        app_logger.error(f"数据库操作失败: {e}", exc_info=True)
        raise
    finally:
        session.close()


def init_database():
    """初始化数据库（创建所有表）"""
    try:
        app_logger.info("开始初始化数据库...")
        Base.metadata.create_all(bind=engine)
        app_logger.info("数据库初始化完成")
    except Exception as e:
        app_logger.error(f"数据库初始化失败: {e}", exc_info=True)
        raise


def drop_all_tables():
    """删除所有表（慎用！）"""
    app_logger.warning("警告：正在删除所有数据库表...")
    Base.metadata.drop_all(bind=engine)
    app_logger.info("所有表已删除")
